#!/bin/bash

echo "🚀 开始部署 AI Daily 前后端服务..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目路径
PROJECT_PATH="/root/ai-daily"
BACKEND_PATH="$PROJECT_PATH/backend"
FRONTEND_PATH="$PROJECT_PATH/frontend"

# 函数：检查命令是否成功
check_success() {
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ $1 成功${NC}"
    else
        echo -e "${RED}❌ $1 失败${NC}"
        exit 1
    fi
}

# 进入项目目录
cd "$PROJECT_PATH" || { echo -e "${RED}❌ 进入目录失败${NC}"; exit 1; }

# 1. 停止现有服务
echo -e "${BLUE}🛑 停止现有服务...${NC}"
if [ -f "stop_services.sh" ]; then
    chmod +x stop_services.sh
    ./stop_services.sh || echo -e "${YELLOW}⚠️ 服务可能未运行${NC}"
else
    echo -e "${YELLOW}⚠️ 停止服务脚本不存在，跳过停止服务${NC}"
fi

# 2. 拉取最新代码
echo -e "${BLUE}🔄 正在拉取最新代码...${NC}"
git fetch --all
git reset --hard origin/master
check_success "拉取最新代码"

# 3. 给脚本添加执行权限
echo -e "${BLUE}🔧 设置脚本执行权限...${NC}"
chmod +x *.sh
check_success "设置执行权限"

# 4. 更新后端
echo -e "${BLUE}🐍 更新后端服务...${NC}"
cd "$BACKEND_PATH" || { echo -e "${RED}❌ 进入后端目录失败${NC}"; exit 1; }

if [ -f "requirements.txt" ]; then
    echo -e "${BLUE}📦 安装后端依赖...${NC}"
    pip3 install -r requirements.txt --no-cache-dir
    check_success "安装后端依赖"
else
    echo -e "${YELLOW}⚠️ 未找到 requirements.txt，跳过安装后端依赖${NC}"
fi

# 5. 更新前端
echo -e "${BLUE}🎨 更新前端服务...${NC}"
cd "$FRONTEND_PATH" || { echo -e "${RED}❌ 进入前端目录失败${NC}"; exit 1; }

if [ -f "package.json" ]; then
    echo -e "${BLUE}📦 安装前端依赖...${NC}"
    npm install
    check_success "安装前端依赖"
    
    echo -e "${BLUE}🏗️ 构建前端...${NC}"
    npm run build
    check_success "构建前端"
else
    echo -e "${YELLOW}⚠️ 未找到 package.json，跳过前端构建${NC}"
fi

# 6. 返回项目根目录并启动服务
cd "$PROJECT_PATH"

echo -e "${BLUE}🚀 启动服务...${NC}"
if [ -f "start_services.sh" ]; then
    ./start_services.sh
    check_success "启动服务"
else
    echo -e "${RED}❌ 启动服务脚本不存在${NC}"
    exit 1
fi

# 7. 检查服务状态
echo -e "${BLUE}📊 检查服务状态...${NC}"
sleep 3
if [ -f "status.sh" ]; then
    ./status.sh
else
    echo -e "${YELLOW}⚠️ 状态检查脚本不存在${NC}"
fi

echo ""
echo -e "${GREEN}🎉 部署完成！${NC}"
echo -e "${BLUE}🔗 前端访问地址: http://localhost:3000${NC}"
echo -e "${BLUE}🔧 后端API地址: http://localhost:8000${NC}"
echo -e "${BLUE}📚 API文档: http://localhost:8000/docs${NC}"